package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.adapter.MyListAdapter;
import com.lily.aidouzixun.adapter.MyViewHolder;
import com.lily.aidouzixun.bean.DynamicCommentInfo;
import com.lily.aidouzixun.bean.DynamicDetailHomeInfo;
import com.lily.aidouzixun.bean.DynamicInfo;
import com.lily.aidouzixun.fragment.DynamicFragment;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.CircleImageView;
import com.lily.aidouzixun.ui.PullToRefreshView;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.DateUtil;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.MySharedPreferences;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 动态详情页
 *
 */
public class DynamicDetailActivity extends Activity {
    private static final String TAG = "DynamicDetailActivity";

    private PullToRefreshView pullToRefreshView;
    private ScrollView sv;
    private TitleBar mTitleBar;
    //private CustomImageView civAvatar;
    private CircleImageView civAvatar;
    private TextView tvNickname;
    private TextView tvPubtime;
    private TextView tvContent;
    private ImageView ivContent;
    private TextView tvSupport;
    private TextView tvComment;
    private TextView tvOpposition;
    private ListView mListView;
    private TextView tvSupportNum;
    private TextView tvCommentNum;
    private TextView tvOppositionNum;
    private static ProgressDialog mProgressDialog; //网络请求时用的进度条

    private Activity mActivity;
    private static Context mContext;
    private static String key = "";
    private static MyHandler mHandler;
    private String backTitle;
    private static final String TITLE = "详情";
    private Bitmap discussPhoto;
    private DynamicInfo discussInfo;
    private MyListAdapter mListAdapter;
    private List<DynamicCommentInfo> discussCommentList;
    private int action;	//用户行为，1-得到新数据;2-得到更多数据
    private int curPageNum = 1;
    private int totalPageNum = 2;
    private int fromType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discussdetail_activity);
        init();
        findViews();
        setListeners();
    }
    /**
     * 初始化参数
     */
    private void init() {
        action = 1;
        this.key += this.hashCode();
        mActivity = DynamicDetailActivity.this;
        mContext = DynamicDetailActivity.this;
        //得到返回标题
        Intent intent = getIntent();
        backTitle = intent.getStringExtra(MyConstant.IntentKey.BACK_TITLE);
        discussInfo = intent.getParcelableExtra(MyConstant.IntentKey.DISCUSSINFO);
        fromType = intent.getIntExtra(MyConstant.IntentKey.FROM_TYPE, 1);
        Log.e(TAG, "init: fromType:" + fromType);
        mHandler = new MyHandler(mActivity);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        mListAdapter = new MyListAdapter(LayoutInflater.from(mContext), MyViewHolder.HolderType.DISCUSS_COMMENT, mContext);
        getCommentData(1);   //得到评论数据
    }
    /**
     * 找到控件
     */
    private void findViews() {
        //标题栏
        mTitleBar = (TitleBar) this.findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);
        pullToRefreshView = (PullToRefreshView) this.findViewById(R.id.refreshable_view);
        pullToRefreshView.setNeedGetMoreData(true);
        pullToRefreshView.setNeedGetNewData(true);
        pullToRefreshView.setFootMode(PullToRefreshView.FootViewMode.ClickAble);
        pullToRefreshView.setOnRefreshListener(refreshListener);
        sv = (ScrollView) this.findViewById(R.id.sv);
        //civAvatar = (CustomImageView) this.findViewById(R.id.user_avatar);
        civAvatar = (CircleImageView) this.findViewById(R.id.user_avatar);
        tvNickname = (TextView) this.findViewById(R.id.tv_nickname);
        tvPubtime = (TextView) this.findViewById(R.id.tv_pubtime);
        tvContent = (TextView) this.findViewById(R.id.tv_discuss_content);
        ivContent = (ImageView) this.findViewById(R.id.iv_discuss);
        tvSupportNum = (TextView) this.findViewById(R.id.tv_left);
        tvCommentNum = (TextView) this.findViewById(R.id.tv_center);
        tvOppositionNum = (TextView) this.findViewById(R.id.tv_right);
        mListView = (ListView) this.findViewById(R.id.lv_discusscomment);
        mListView.setAdapter(mListAdapter);

        tvSupport = (TextView) this.findViewById(R.id.tv_support);
        if (discussInfo.getIsSupport() == 1) {  //赞过了
            tvSupport.setSelected(true);
        } else {
            tvSupport.setSelected(false);
        }
        tvComment = (TextView) this.findViewById(R.id.tv_comment);
        tvOpposition = (TextView) this.findViewById(R.id.tv_opposition);
        if (discussInfo.getIsCollect() == 1) {  //收藏过了
            tvOpposition.setSelected(true);
        } else {
            tvOpposition.setSelected(false);
        }
        if (discussInfo != null) {
            tvNickname.setText(discussInfo.getNickName());
            tvPubtime.setText(DateUtil.timeLogic(discussInfo.getPubtime()));
            tvContent.setText(discussInfo.getContent());
            Glide.with(mContext).load(discussInfo.getAvatar()).placeholder(R.mipmap.my_launcher).into(civAvatar);

            if (Validator.isEffective(discussInfo.getImageUrl())) {
                Glide.with(mContext)
                        .load(discussInfo.getImageUrl())
                        .into(ivContent);
            } else {
                ivContent.setVisibility(View.GONE);
            }
            tvSupportNum.setText("赞  " + discussInfo.getSupport());
            tvCommentNum.setText("评论  " + discussInfo.getComments());
            tvOppositionNum.setText("收藏  " + discussInfo.getOpposition());
        }
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //图片
        ivContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ShowImageActivity.class);
                intent.putExtra(MyConstant.IntentKey.IMAGE_FROM, ShowImageActivity.ImageFrom.URL);
                intent.putExtra(MyConstant.IntentKey.IMAGE_URL, discussInfo.getImageUrl());
                startActivity(intent);
            }
        });
        //点赞
        tvSupport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyConfig.isLogined(mContext)) {
                    MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, true);
                    if (discussInfo.getIsSupport() == 1) {
                        if (fromType == 1) {
                            DynamicFragment.support(discussInfo.getDid(), DynamicFragment.ActionType.DOWN);
                        } else if (fromType == 2){
                            DynamicCollectActivity.support(discussInfo.getDid(), DynamicFragment.ActionType.DOWN);
                        } else {
                            DynamicMineActivity.support(discussInfo.getDid(), DynamicFragment.ActionType.DOWN);
                        }
                        discussInfo.setSupport(discussInfo.getSupport() - 1);
                        tvSupportNum.setText("赞  " + discussInfo.getSupport());
                        discussInfo.setIsSupport(0);
                        tvSupport.setSelected(false);
                    } else {
                        if (fromType == 1) {
                            DynamicFragment.support(discussInfo.getDid(), DynamicFragment.ActionType.UP);
                        } else if (fromType == 2){
                            DynamicCollectActivity.support(discussInfo.getDid(), DynamicFragment.ActionType.UP);
                        } else {
                            DynamicMineActivity.support(discussInfo.getDid(), DynamicFragment.ActionType.UP);
                        }
                        discussInfo.setSupport(discussInfo.getSupport() + 1);
                        tvSupportNum.setText("赞  " + discussInfo.getSupport());
                        discussInfo.setIsSupport(1);
                        tvSupport.setSelected(true);
                    }
                } else {
                    gotoLoginActivity();
                }
            }
        });
        //评论
        tvComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyConfig.isLogined(mContext)) {
                    Intent commentIntent = new Intent(mContext, CommentActivity.class);
                    String did = discussInfo.getDid();
                    commentIntent.putExtra(MyConstant.IntentKey.COMMENT_FROM, CommentActivity.FromType.DISCUSS_DETAIL);
                    commentIntent.putExtra(MyConstant.IntentKey.DID, did);
                    startActivityForResult(commentIntent, MyConstant.IntentForResultCODE.DISCUSS_COMMENT_REQUESTCODE);
                } else {
                    gotoLoginActivity();
                }
            }
        });
        //收藏
        tvOpposition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyConfig.isLogined(mContext)) {
                    MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, true);
                    if (discussInfo.getIsCollect() == 1) {
                        if (fromType == 1) {
                            DynamicFragment.collect(discussInfo.getDid(), DynamicFragment.ActionType.DOWN);
                        } else if (fromType == 2){
                            DynamicCollectActivity.collect(discussInfo.getDid(), DynamicFragment.ActionType.DOWN);
                        } else{
                            DynamicMineActivity.collect(discussInfo.getDid(), DynamicFragment.ActionType.DOWN);
                        }
                        discussInfo.setOpposition(discussInfo.getOpposition() - 1);
                        tvOppositionNum.setText("收藏  " + discussInfo.getOpposition());
                        discussInfo.setIsCollect(0);
                        tvOpposition.setSelected(false);
                    } else {
                        if (fromType == 1) {
                            DynamicFragment.collect(discussInfo.getDid(), DynamicFragment.ActionType.UP);
                        } else  if (fromType == 2){
                            DynamicCollectActivity.collect(discussInfo.getDid(), DynamicFragment.ActionType.UP);
                        } else {
                            DynamicMineActivity.collect(discussInfo.getDid(), DynamicFragment.ActionType.UP);
                        }
                        discussInfo.setOpposition(discussInfo.getOpposition() + 1);
                        tvOppositionNum.setText("收藏  " + discussInfo.getOpposition());
                        discussInfo.setIsCollect(1);
                        tvOpposition.setSelected(true);
                    }
                } else {
                    gotoLoginActivity();
                }
            }
        });
    }

    /**
     * 点赞
     * @param did
     * @param actionType 操作类型：1：点赞；-1：取消点赞
     */
    public static void support(String did, int actionType) {
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.SUPPORT_DISCUSS);
        param.put(MyConstant.RequireParams.MAP_KEY, key + MyConstant.DataType.SUPPORT_DISCUSS);
        param.put(MyConstant.RequireParams.DID, did);
        param.put(MyConstant.RequireParams.ACTION, actionType);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 跳转到登录界面
     */
    public void gotoLoginActivity() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra(MyConstant.IntentKey.BACK_TITLE, TITLE);
        startActivityForResult(intent, MyConstant.IntentForResultCODE.LOGIN_REQUESTCODE);
    }

    /**
     * 接收回传信息
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case MyConstant.IntentForResultCODE.DISCUSS_COMMENT_REQUESTCODE:
                getCommentData(1);
                break;

            default:
                break;
        }
    }

    /**
     * 得到评论数据
     */
    private void getCommentData(int pager) {
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.COMMENT_DATA);
        if (Validator.isEffective(discussInfo.getDid())) {
            param.put(MyConstant.RequireParams.DID, discussInfo.getDid());
        }
        param.put(MyConstant.RequireParams.PAGE, pager);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.COMMENT_DATA);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 得到评论数据完成
     * @param discussDetailHomeInfo
     */
    private void getCommentFnished(DynamicDetailHomeInfo discussDetailHomeInfo) {
        curPageNum = discussDetailHomeInfo.getCurpage();
        totalPageNum = discussDetailHomeInfo.getTotalpage();
        if (discussCommentList == null || action == 1) {
            discussCommentList = new ArrayList<DynamicCommentInfo>();
        }
        for (int i =0; i < discussDetailHomeInfo.getCommentList().size(); i++) {
            discussCommentList.add(discussDetailHomeInfo.getCommentList().get(i));
        }
        mListAdapter.setData(discussCommentList);
        if (action == 1) {
            sv.smoothScrollTo(0,0);
            mListView.setFocusable(false);
        }
        mListAdapter.notifyDataSetChanged();
        pullToRefreshView.onHeaderRefreshComplete();
        pullToRefreshView.onComplete(false);
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final DynamicDetailActivity activity = (DynamicDetailActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:
                            /*if (msg.arg1 == MyConstant.DataType.COMMENT_DATA) {
                                if (activity.mProgressDialog != null) {
                                    activity.mProgressDialog.setMessage("正在加载数据...");
                                    activity.mProgressDialog.show();
                                }
                            }*/
                            break;
                        case MessageType.CLOSE_DIALOG:
                            /*if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.dismiss();
                            }*/
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED:
                            if (msg.arg1 == MyConstant.DataType.COMMENT_DATA) {
                                SparseArray<Object> commentResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) commentResult.get(0);
                                if ("0".equals(errno)) {
                                    DynamicDetailHomeInfo discussDetailHomeInfo = (DynamicDetailHomeInfo) commentResult.get(2);
                                    if (discussDetailHomeInfo != null) {
                                        //处理得到评论数据完成
                                        activity.getCommentFnished(discussDetailHomeInfo);
                                    }
                                }
                            } else if (msg.arg1 == MyConstant.DataType.SUPPORT_DISCUSS) {   //点赞
                                SparseArray<Object> supportResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) supportResult.get(0);
                                if ("0".equals(errno)) {    //点赞成功

                                }
                            } else if (msg.arg1 == MyConstant.DataType.OPPOSITION_DISCUSS) {    //反对

                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }

    PullToRefreshView.OnRefreshListener refreshListener = new PullToRefreshView.OnRefreshListener() {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub
            action = 1;
            getCommentData(1);
        }

        @Override
        public boolean onMore(int nextPageNum) {
            // TODO Auto-generated method stub
            action = 2;
            if(curPageNum < totalPageNum) {
                getCommentData(curPageNum + 1);
                return true;
            } else {
                pullToRefreshView.onComplete(false);
                return false;
            }
        }

        @Override
        public void onGetPageData() {
            // TODO Auto-generated method stub
        }

    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
}
